import { convertEmoji, formatNum } from '../util'
import { Contact_Data, Contact, getDisplayName, isRoomContact } from "./contact"
import Wechat from "../wechat"
export interface Message_Data {
  FromUserName: string;
  ToUserName: string;
  Content: string;
  StatusNotifyUserName: string;
  ImgWidth: number;
  PlayLength: number;
  RecommendInfo: any;
  StatusNotifyCode: number;
  NewMsgId: string;
  Status: number;
  VoiceLength: number;
  ForwardFlag: number;
  AppMsgType: number;
  Ticket: string;
  AppInfo: any;
  Url: string;
  ImgStatus: number;
  MsgType: number;
  ImgHeight: number;
  MediaId: string;
  MsgId: string;
  FileName: string;
  HasProductId: number;
  FileSize: string;
  CreateTime: number;
  SubMsgType: number;
}
/* Message Object Example
{
    "FromUserName": "",
    "ToUserName": "",
    "Content": "",
    "StatusNotifyUserName": "",
    "ImgWidth": 0,
    "PlayLength": 0,
    "RecommendInfo": {},
    "StatusNotifyCode": 4,
    "NewMsgId": "",
    "Status": 3,
    "VoiceLength": 0,
    "ForwardFlag": 0,
    "AppMsgType": 0,
    "Ticket": "",
    "AppInfo": {...},
    "Url": "",
    "ImgStatus": 1,
    "MsgType": 1,
    "ImgHeight": 0,
    "MediaId": "",
    "MsgId": "",
    "FileName": "",
    "HasProductId": 0,
    "FileSize": "",
    "CreateTime": 0,
    "SubMsgType": 0
}
*/
export class Message implements Message_Data {
  public FromUserName: string;
  public ToUserName: string;
  public Content: string;
  public StatusNotifyUserName: string;
  public ImgWidth: number;
  public PlayLength: number;
  public RecommendInfo: any;
  public StatusNotifyCode: number;
  public NewMsgId: string;
  public Status: number;
  public VoiceLength: number;
  public ForwardFlag: number;
  public AppMsgType: number;
  public Ticket: string;
  public AppInfo: any;
  public Url: string;
  public ImgStatus: number;
  public MsgType: number;
  public ImgHeight: number;
  public MediaId: string;
  public MsgId: string;
  public FileName: string;
  public HasProductId: number;
  public FileSize: string;
  public CreateTime: number;
  public SubMsgType: number;
  // public static createInstance(data: Message_Data, instance: any): Message {
  //   let ins = Object.setPrototypeOf(data, Message);
  //   ins.init(instance);
  //   return ins;
  // }
  //群消息，其他人发的FromUserName永远是群，所以需要转换成谁发的
  //群消息,toUserName永远都是自己
  //OriginalContent 如果是别人发的是用的username：什么，如果是自己发的用的是昵称
  public isSendBySelf: boolean = false;
  public OriginalContent: string = "";
  public toUser: Contact_Data = null;//真是的接收者，如果是群的@就是被@的人
  public fromUser: Contact_Data = null;//真是的发送者，群就是成员
  private weChatIns: Wechat = null;
  public isGroupMsg: boolean = false;
  public isRoomAt: boolean = false;

  constructor(data: Message_Data, instance: Wechat) {
    for (let key in data) {
      this[key] = data[key];
    }
    this.init(instance);
    this.weChatIns = instance;
  }
  public init(instance: Wechat) {
    this.MsgType = +this.MsgType
    this.isSendBySelf = this.FromUserName === instance.user.UserName || this.FromUserName === ''
    this.toUser = instance.contacts[this.ToUserName];
    this.fromUser = this.isSendBySelf ? instance.user : instance.contacts[this.FromUserName];
    this.OriginalContent = this.Content;
    this.isGroupMsg = (/^@@|@chatroom$/.test(this.ToUserName) || /^@@|@chatroom$/.test(this.FromUserName));
    //要计算出如果是群那么就要算接收者
    this.Content = this.Content.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/<br\/>/g, '\n');
    if (/^@@|@chatroom$/.test(this.isSendBySelf ? this.ToUserName : this.FromUserName)) {
      this.isRoomAt = (this.Content.indexOf("@") == 0 && this.Content.indexOf("\u2005") != -1);
    }
    if (this.isSendBySelf) {
      if (/^@@|@chatroom$/.test(this.ToUserName)) {
        //我发送的群消息，这时候全部都是昵称，from是我自己，to是群，所以如果是@就要修改touser为真是的人
        //我发的内容就直接ok了
        if (this.isRoomAt) {
          let pos = this.Content.indexOf("\u2005");
          let userNickName = this.Content.substring(1, pos);
          this.Content = this.Content.substr(pos).replace("\u2005", "");
          this.toUser = instance.contacts[this.ToUserName].MemberList.find((member: Contact_Data) => {
            return member.UserName === userNickName || member.NickName === userNickName || member.RemarkName === userNickName || member.DisplayName === userNickName;
          });
          if (this.toUser == null) {
            this.toUser = instance.contacts[this.ToUserName];
            this.isRoomAt = false;
          }
        }
      }
    } else {
      if (/^@@|@chatroom$/.test(this.FromUserName)) {
        //群消息，别人发的，这时候from是群，to是我自己，修改from为真实的人
        if (this.MsgType != instance.CONF.MSGTYPE_SYS) {
          let pos = this.Content.indexOf(":\n");
          let fromUserName = this.Content.substring(0, pos);

          this.Content = this.Content.substr(pos).replace(":\n", "");
          this.fromUser = instance.contacts[this.FromUserName].MemberList.find((member: Contact_Data) => {
            return member.UserName === fromUserName;
          })
          if (getDisplayName(this.fromUser) == "") {

            try {
              // instance.batchGetContact([{ UserName: fromUserName, EncryChatRoomId: instance.contacts[this.FromUserName].EncryChatRoomId }]).then(contacts => {
              //   instance.updateContacts(contacts);
              // });

              instance.batchGetContact([{ UserName: this.FromUserName }]).then(contacts => {
                instance.updateContacts(contacts);
              });

            } catch (err) {

            }
          }
          //如果是@修改to为真实的人，否则to应该是群
          if (this.isRoomAt) {
            let pos = this.Content.indexOf("\u2005");
            let userNickName = this.Content.substring(1, pos);
            this.Content = this.Content.substr(pos).replace("\u2005", "");
            this.toUser = instance.contacts[this.FromUserName].MemberList.find((member: Contact_Data) => {
              return member.UserName === userNickName || member.NickName === userNickName || member.RemarkName === userNickName || member.DisplayName === userNickName;
            })
            if (this.toUser == null) {
              this.toUser = instance.contacts[this.FromUserName];
              this.isRoomAt = false;
            }
          } else {
            this.toUser = instance.contacts[this.FromUserName];
          }
        }
        //还要修改内容

      }
    }

    // if (this.FromUserName.indexOf('@@') === 0) {
    //   this.toUser = instance.contacts[this.FromUserName];
    //   this.Content = this.Content.replace(/^@.*?(?=:)/, match => {
    //     let user = instance.contacts[this.FromUserName].MemberList.find((member: Contact_Data) => {
    //       return member.UserName === match
    //     })
    //     return user ? getDisplayName(user) : match
    //   })
    // }
    // if (this.isRoomAt()) {
    //   let pos = this.OriginalContent.indexOf("\u2005");
    //   let userNickName = this.OriginalContent.substring(1, pos);
    //   this.Content = this.OriginalContent.substr(pos).replace("\u2005", "");
    //   this.toUser = instance.contacts[this.ToUserName].MemberList.find((member: Contact_Data) => {
    //     return member.UserName === userNickName || member.NickName === userNickName || member.RemarkName === userNickName || member.DisplayName === userNickName;
    //   })
    // }

    this.Content = convertEmoji(this.Content)

    return this
  }
  public isSendBy(contact: Contact_Data): boolean {
    return this.FromUserName === contact.UserName
  }
  public getPeerUserName(): string {
    return this.isSendBySelf ? this.ToUserName : this.FromUserName
  }
  public getDisplayTime(): string {
    var time = new Date(1e3 * this.CreateTime)
    return time.getHours() + ':' + formatNum(time.getMinutes(), 2)
  }
}
